
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class EchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public EchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动!"); 
        while (true) {
            // 1. 从控制台读取用户输入的内容
            System.out.print("> ");
            String request = scanner.next();
            // 2. 构造成 UDP 请求, 并发送. 不光要填内容, 还要填服务器的地址和端口.
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, 
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(reqPacket);
            // 3. 读取服务器的响应.
            DatagramPacket respPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respPacket);
            String response = new String(respPacket.getData(), 0, respPacket.getLength());
            // 4. 把响应显示到控制台.
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient("101.200.34.238", 9090);
        echoClient.start();
    }
}
